<?php

namespace zhtfrontend\models\datas;

use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use common\models\datas\CustomerBranchaccount;
use common\models\datas\Payment;
use common\models\datas\Customer;
use common\models\datas\Student;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

/**
 * This is the model class for table "{{%orders}}".
 *
 * @property integer $id
 * @property string $sn
 * @property string $total_amount
 * @property string $final_amount
 * @property integer $pay_status
 * @property integer $ship_status
 * @property integer $payment_id
 * @property integer $shipping_id
 * @property string $shipping_name
 * @property integer $customer_id
 * @property integer $status
 * @property string $weight
 * @property string $remarks
 * @property integer $item_num
 * @property string $ip
 * @property string $item_amount
 * @property integer $is_invoice
 * @property string $invoice_type
 * @property string $invoice_title
 * @property integer $is_protect
 * @property string $cost_protect
 * @property string $discount_amount
 * @property string $freight
 * @property string $order_source
 * @property integer $give_points
 * @property integer $use_points
 * @property integer $ship_time
 * @property integer $is_delete
 * @property integer $is_comment
 * @property integer $update_at
 * @property integer $created_at
 * @property string $order_type
 * @property string $telephone
 * @property integer $pay_time
 * @property integer $customer_card
 * @property integer $cash_money
 */
class Orders extends \zhtfrontend\components\bases\BaseModel
{
    public $goods_id;//获取所选商品的id
    public $password; //会员登陆密码
    public $password_r;//正确密码
    public $account;//账户余额
    public $pay_password;//账户余额
    public $skill_class_num;
    public $skill_class_price;
    public $art_class_num;
    public $art_class_price;
    public $art_id;
    public $goods_price_id;
    public $IDcard;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%orders}}';
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['total_amount', 'account_money', 'final_amount', 'weight', 'item_amount', 'cost_protect', 'discount_amount', 'freight','scholarship_money','cash_money','account','remain_amount','deposit','skill_class_price','art_class_price'], 'number'],
            [['pay_status', 'ship_status', 'payment_id', 'shipping_id', 'customer_id', 'status', 'is_invoice', 'is_protect', 'give_points', 'use_points', 'ship_time', 'is_delete', 'is_comment', 'updated_at', 'created_at','telephone','pay_time','skill_class_num','art_class_num','art_id','goods_price_id','type_id'], 'integer'],
            [['sn','customer_card'], 'string', 'max' => 150],
            [['shipping_name', 'order_type'], 'string', 'max' => 50],
            [['remarks'], 'string', 'max' => 225],
            [['ip', 'invoice_title','IDcard'], 'string', 'max' => 100],
            [['invoice_type', 'order_source'], 'string', 'max' => 20],
            [['total_amount', 'final_amount'], 'compare', 'compareValue' => 0, 'operator' => '>=', 'on' => ['consume', 'order', 'transform']],
           // [['password'], 'required', 'message' => '请输入密码', 'on' => ['consume', 'order', 'transform','transfer']],
            //[['final_amount'], 'account_check','on' => ['orderproduct']],
           // [['password'], 'password_check', 'on' => ['consume', 'order', 'transform','transfer']],
            //[['pay_password'], 'validate_password', 'skipOnEmpty'=>false, 'on' => ['orderproduct']],
            [['goods_id'], 'required', 'on' => ['consume', 'order', 'transform','transfer','orderproduct']],
            //[['skill_class_num'], 'required', 'on' => ['transform']],
           // [['art_class_num'], 'existence_art', 'skipOnEmpty'=>false,  'on' => ['transform']],
          //  [['final_amount'], 'order_account_check', 'on' => ['order']],
            ['IDcard','validate_card','skipOnEmpty'=>false,'on'=>['conformcourse']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', '自增编号'),
            'sn' => Yii::t('zhtfrontend', '订单编号'),
            'total_amount' => Yii::t('zhtfrontend', '订单总价'),
            'final_amount' => Yii::t('zhtfrontend', '实付价格'),
            'pay_status' => Yii::t('zhtfrontend', '支付状态付款状态 （0:未支付;1:已支付;2:已付款至到担保方;3:部分付款;4:部分退款;5:全额退款; ）'),
            'ship_status' => Yii::t('zhtfrontend', '发货状态（ 0:未发货;1无需发货 ;2:已发货;3:部分发货;4:部分退货;5:已退货）'),
            'payment_id' => Yii::t('zhtfrontend', '支付方式id'),
            'shipping_id' => Yii::t('zhtfrontend', '配送方式id'),
            'shipping_name' => Yii::t('zhtfrontend', '配送方式名称'),
            'customer_id' => Yii::t('zhtfrontend', '会员id'),
            'status' => Yii::t('zhtfrontend', '订单状态。（0，未确认；1，已确认；2，已取消；3，无效；4，退货；5 已完成）'),
            'weight' => Yii::t('zhtfrontend', '订单总重量(单位kg)'),
            'remarks' => Yii::t('zhtfrontend', '备注'),
            'item_num' => Yii::t('zhtfrontend', '订单商品数量'),
            'ip' => Yii::t('zhtfrontend', '下单IP'),
            'item_amount' => Yii::t('zhtfrontend', '商品总价格'),
            'is_invoice' => Yii::t('zhtfrontend', '是否开发票（1 是 0 否）'),
            'invoice_type' => Yii::t('zhtfrontend', '发票类型（false:不需发票;personal:个人发票;company:公司发票）'),
            'invoice_title' => Yii::t('zhtfrontend', '发票抬头'),
            'is_protect' => Yii::t('zhtfrontend', '是否保价（1 是 0 否） '),
            'cost_protect' => Yii::t('zhtfrontend', '保价费(根据商品价格自动计算保价费)'),
            'discount_amount' => Yii::t('zhtfrontend', '优惠总价'),
            'freight' => Yii::t('zhtfrontend', '配送费'),
            'order_source' => Yii::t('zhtfrontend', '订单来源（pc/app/wechat）'),
            'give_points' => Yii::t('zhtfrontend', '奖励积分'),
            'use_points' => Yii::t('zhtfrontend', '使用积分'),
            'ship_time' => Yii::t('zhtfrontend', '发货时间'),
            'is_delete' => Yii::t('zhtfrontend', '是否删除（1正常 0 删除）'),
            'is_comment' => Yii::t('zhtfrontend', '是否评价（1是 0 否）'),
            'updated_at' => Yii::t('zhtfrontend', '更新时间'),
            'created_at' => Yii::t('zhtfrontend', '下单时间'),
            'order_type' => Yii::t('zhtfrontend', '订单类型（normal；appointment;转化conversion,续费renew,保证金转学费deposittransform）'),
            'associate_id' => Yii::t('zhtfrontend', '关联订单id'),
            'telephone' => Yii::t('zhtfrontend', '联系电话'),
            'pay_time' => Yii::t('zhtfrontend', '支付时间'),
            'scholarship_money' => Yii::t('zhtfrontend', '扣除奖学金'),
            'cash_money' => Yii::t('zhtfrontend', '扣除余额'),
            'goods_id'  => Yii::t('zhtfrontend','课程id'),
            'password'  => Yii::t('zhtfrontend','登录密码'),
            'account' => Yii::t('zhtfrontend', '账户余额'),
            'password_r' => Yii::t('zhtfrontend', '正确密码'),
            'remain_amount' => Yii::t('zhtfrontend','最终金额(有退款减去退款金额)'),
            'deposit' => Yii::t('zhtfrontend','订单支付保证金金额'),
            'pay_password' => Yii::t('common','支付密码'),
            'customer_card' => Yii::t('common','会员卡号'),
            'art_class_num' => Yii::t('common','艺教学课次数'),
            'art_class_price' => Yii::t('common','单节艺教学课次价格'),
            'skill_class_num' => Yii::t('common','技教学课次数'),
            'skill_class_price' => Yii::t('common','单节技教学课次价格'),
            'mechanic_id' => Yii::t('common','机构id'),
            'art_id' => Yii::t('common','艺教学id'),
            'goods_price_id' => Yii::t('common','商品价格id'),
            'type_id' => Yii::t('common','类型'),
            'IDcard' => Yii::t('common','学员身份证号'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['href'] = function () {
            return  Url::to(['appointment/index','customer_id'=>$this->customer_id],true);
        };
        $fields['goods_name'] = function () {
            $items=$this->ordersItems;
            return !empty($items)?$items[0]->name:'未知';
        };
        $fields['pay_time'] = function () {
            if($this->pay_time == 0){
                return \Yii::t('zhtfrontend','未付款');
            }else{
                return \Yii::$app->formatter->asDatetime($this->pay_time);
            }
        };
        $fields['ship_time'] = function () {
            if($this->ship_status == 1){
                return \Yii::t('zhtfrontend','无需发货');
            }else{
                if($this->ship_time == 0){
                    return \Yii::t('zhtfrontend','未发货');
                }else{
                    return \Yii::$app->formatter->asDatetime($this->pay_time);
                }
            }
        };
        $fields['telephone'] = function () {
            return !empty($this->telephone)?$this->telephone:($this->customer != null?$this->customer->mobile:'');
        };
        $fields['pay_status_desc']=function(){
        switch($this->pay_status){
            case 0:
                return \Yii::t('zhtfrontend','未支付');
            case 1:
                return \Yii::t('zhtfrontend','已支付');
            case 2:
                return \Yii::t('zhtfrontend','已付款至到担保方');
            case 3:
                return \Yii::t('zhtfrontend','部分付款');
            case 4:
                return \Yii::t('zhtfrontend','部分退款');
            case 5:
                return \Yii::t('zhtfrontend','全额退款');
            default:
                return \Yii::t('zhtfrontend','订单支付状态更改');
        }
    };

        return $fields;
    }

    public function extraFields(){
        return [
            'customer_name' => function(){
                return isset($this->customer)?$this->customer->name:'';
            },
            'card_id' => function(){
                return isset($this->customer)?$this->customer->card_id:'';
            },
            'customer_created_at' => function(){
                return isset($this->customer)?\Yii::$app->formatter->asDatetime($this->customer->created_at):'';
            },
            'status_name' => function(){
                switch($this->status){
                    case 0:
                        return \Yii::t('zhtfrontend', '未确认');
                    case 1:
                        return \Yii::t('zhtfrontend', '已确认');
                    case 2:
                        return \Yii::t('zhtfrontend','已取消');
                    case 3:
                        return \Yii::t('zhtfrontend','无效');
                    case 4:
                        return \Yii::t('zhtfrontend','已退货');
                    case 5:
                        return \Yii::t('zhtfrontend','部分退货');
                    case 6:
                        return \Yii::t('zhtfrontend','已完成');
                    case 7:
                        return \Yii::t('zhtfrontend','转化');
                    case 8:
                        return \Yii::t('zhtfrontend','续费');
                }
            },
        'pay_status_name' => function(){
            switch($this->pay_status){
                case 0:
                    return \Yii::t('zhtfrontend','未支付');
                case 1:
                    return \Yii::t('zhtfrontend','已支付');
                case 2:
                    return \Yii::t('zhtfrontend','已付款至到担保方');
                case 3:
                    return \Yii::t('zhtfrontend','部分付款');
                case 4:
                    return \Yii::t('zhtfrontend','部分退款');
                case 5:
                    return \Yii::t('zhtfrontend','全额退款');
            }
        },
        'ship_status_name' => function(){
            switch($this->ship_status){
                case 0:
                    return \Yii::t('zhtfrontend','未发货');
                case 1:
                    return \Yii::t('zhtfrontend','无需发货');
                case 2:
                    return \Yii::t('zhtfrontend','已发货');
                case 3:
                    return \Yii::t('zhtfrontend','部分发货');
                case 4:
                    return \Yii::t('zhtfrontend','部分退货');
                case 5:
                    return \Yii::t('zhtfrontend','已退货');
            }
        },
        'appointment_name' => function(){
            switch($this->order_type){
                case 'normal':
                    return \Yii::t('zhtfrontend','正常订单');
                case 'appointment':
                    return \Yii::t('zhtfrontend','预约订单');
                case 'conversion':
                    return \Yii::t('zhtfrontend','转化订单');
                case 'renew':
                    return \Yii::t('zhtfrontend','续费订单');
            }
        },
            'payment_name' => function(){
                return isset($this->payment)?$this->payment->name:'';
            },
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
            'orderitem_id' => function(){
                return isset($this->ordersItems->id)?$this->ordersItems->id:0;
            }
        ];

    }

    //验证消费余额

    public function account_check($attribute)
    {
        $account = CustomerBranchaccount::find()->where(['customer_id'=>$this->customer_id,'site_id'=>Fun::getSiteId(),'mode'=>2])->one();
        if(($account == null) || $account->cash < $this->final_amount)
            $this->addError($attribute, Yii::t('zhtfrontend', '账户余额不足,请先充值'));
    }

    //验证消费余额
    public function order_account_check($attribute)
    {
        $account = CustomerBranchaccount::find()->where(['customer_id'=>$this->customer_id,'site_id'=>Fun::getSiteId(),'mode'=>2])->one();
        if (($account == null) || ($account->scholarship_available+$account->cash) < $this->final_amount)
            $this->addError($attribute, Yii::t('zhtfrontend', '账户余额不足,请先充值'));

    }

    public function password_check($attribute)
    {
        if ($this->password_r == null) {
            $this->addError($attribute, \Yii::t('zhtfrontend', '请先设置密码'));
        } else {
            if (!(\Yii::$app->security->validatePassword($this->password, $this->password_r))) {
                $this->addError($attribute, \Yii::t('zhtfrontend', '密码不正确'));
            }
        }

    }
    //验证支付订单时的总金额
    function validate_password($attribute){
        $branch = CustomerBranchaccount::find()->where(['site_id'=>Fun::getSiteId(),'customer_id'=>$this->customer_id])->one();
        if($branch->pay_password != md5($this->$attribute)){
            $this->addError($attribute, Yii::t('common', '支付密码不正确！'));
        }


    }

    //验证身份证号
    public function validate_card($attribute){
        $student = Student::find()->where(['customer_id'=>$this->customer_id])->one();
        if($student->IDcard == null || empty($student->IDcard)){
            if(empty($this->$attribute)){
                $this->addError($attribute, \Yii::t('common', '身份证不能为空！'));
            }else {
                $id = strtoupper($this->$attribute);
                $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
                $arr_split = array();
                if (!preg_match($regx, $id)) {
                    $this->addError($attribute, Yii::t('common', '身份证号不合法！'));
                }
                if (15 == strlen($id)) {
                    $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

                    @preg_match($regx, $id, $arr_split);
                    //检查生日日期是否正确
                    $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
                    if (!strtotime($dtm_birth)) {
                        $this->addError($attribute, Yii::t('common', '身份证号不合法！'));
                    }else{
                        $sub_str = (int)substr($id, 6, 4);
                        $now = (int)date("Y", time());
                        if ($now - $sub_str > 18) {
                            $this->addError($attribute, Yii::t('common', '学员年龄不能大于18岁！'));
                        }
                    }
                } elseif (strlen($id) == 18) {
                    $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
                    @preg_match($regx, $id, $arr_split);
                    $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
                    if (!strtotime($dtm_birth)) //检查生日日期是否正确
                    {
                        $this->addError($attribute, Yii::t('common', '身份证号不合法！'));
                    } else {
                        //检验18位身份证的校验码是否正确。
                        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                        $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                        $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                        $sign = 0;
                        for ($i = 0; $i < 17; $i++) {
                            $b = (int)$id{$i};
                            $w = $arr_int[$i];
                            $sign += $b * $w;
                        }
                        $n = $sign % 11;
                        $val_num = $arr_ch[$n];
                        if ($val_num != substr($id, 17, 1)) {
                            $this->addError($attribute, Yii::t('common', '身份证号不合法！'));
                        }else{
                            $sub_str = (int)substr($id, 6, 4);
                            $now = (int)date("Y", time());
                            if ($now - $sub_str > 18) {
                                $this->addError($attribute, Yii::t('common', '学员年龄不能大于18岁！'));
                            }
                        }
                    }
                }else{
                    $this->addError($attribute, Yii::t('common', '身份证号不合法！'));
                }
            }
        }

    }

    public function existence_art($attribute){
        $group = GoodsGroup::find()->where(['goods_id'=>$this->goods_id])->one();
        if($group != null){
            if(empty($this->$attribute)){
                $this->addError($attribute, Yii::t('common', '填写课次数！'));
            }
        }
    }
    public function getOrdersItems(){
        return $this->hasMany(OrdersItems::className(),['orders_id'=>'id']);
    }

    public function getCustomer(){
        return $this->hasOne(Customer::className(),['id'=>'customer_id']);
    }

    public function getPayment(){
        return $this->hasOne(Payment::className(),['id'=>'payment_id']);
    }

    public function getMechanic(){
        return $this->hasOne(Mechanic::className(),['id'=>'mechanic_id']);
    }

    public function getAssociate(){
        return $this->hasOne(Orders::className(),['associate_id'=>'id']);
    }
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
        ]);
    }

    public function afterSave($insert,$changedAttributes){
        parent::afterSave($insert,$changedAttributes);
            if($insert){ //订单提交是插入记录
                $orderLog = new OrdersLog();
                $orderLog->orders_id = $this->id;
                $orderLog->operator_id = \Yii::$app->user->id;
                $orderLog->operator_name = \Yii::$app->user->identity->name;
                $orderLog->status = 0;
                $orderLog->result = 'SUCCESS';
                $orderLog->log_text = '提交了订单';
                $orderLog->alttime = time();
                $orderLog->save(false);
            }

    }

    public function getOrderstype(){
        return $this->hasMany(OrdersType::className(),['orders_id'=>'id']);
    }
}
